package com.lsh.airticket.filter;

import cn.hutool.core.codec.Base64;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.gson.JsonObject;
import com.lsh.airticket.exception.UserException;
import com.lsh.airticket.util.JWTUtil;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 全局Filter，统一处理会员登录与外部不允许访问的服务
 * </p>
 *
 * @author qy
 * @since 2019-11-21
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        System.out.println(path);
        if ("/users/user/login".equals(path)) {
            return chain.filter(exchange);
        }
        if (path.contains("/flights/flight")) {
            return chain.filter(exchange);
        }
        if (path.contains("/flights/city")) {
            return chain.filter(exchange);
        }
        if (path.contains("/flights/ticket")) {
            return chain.filter(exchange);
        }
        if (path.contains("/sms/sendSMS")) {
            return chain.filter(exchange);
        }
        if (path.contains("/users/user/smsLogin")) {
            System.out.println(1111);
            return chain.filter(exchange);
        }if (path.contains("/users/admin/login")) {
            System.out.println(1111);
            return chain.filter(exchange);
        }




        System.out.println("登录拦截器");

        System.out.println(request.getMethod());


        // //从头中获取token字符串
        List<String> tokens = request.getHeaders().get("token");
        System.out.println(tokens);
        if (tokens == null || tokens.size() <1) {

            //token 不存在抛异常
            return out(exchange.getResponse(),"请登录！", 3);
            // throw new UserException("请登录！", 3);
        }
        String token = tokens.get(0);

        Map<String, Object> user = null;
        try {
            token = Base64.decodeStr(token);
            DecodedJWT verify = JWTUtil.verify(token);
            user = verify.getClaim("user").asMap();
        } catch (Exception e) {
            e.printStackTrace();
            //token 不合法抛异常  4表示用户失效
            return out(exchange.getResponse(),"用户已失效！", 4);
            // throw new UserException("用户已失效！", 4);
        }

        //获取标志位
        Integer flag = (Integer) user.get("flag");

        // 判断是不是管理员登录
        // String servletPath = request.getServletPath();
        String servletPath = request.getURI().getPath();
        // System.out.println(servletPath);
        if (servletPath.contains("/admin")) {
            System.out.println("包含");
            if (flag != null && flag != 1) {
                return out(exchange.getResponse(),"没有管理员权限", 5);
                // throw new UserException("没有管理员权限", 5);
            }

        } else {
            if (flag != null && flag != 2) {
                return out(exchange.getResponse(),"请用用户身份登录", 6);
                // throw new UserException("请用用户身份登录", 6);
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> out(ServerHttpResponse response,String msg, Integer status) {
        JsonObject message = new JsonObject();
        message.addProperty("msg", msg);
        message.addProperty("status", status);
        byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
